// scripts/auth.js
// 注册功能
document.getElementById('registerForm').addEventListener('submit', (e) => {
    e.preventDefault();
    const username = document.getElementById('regUsername').value;
    const email = document.getElementById('regEmail').value;
    const password = document.getElementById('regPassword').value;

    if(!validateEmail(email)) {
        showError('邮箱格式不正确');
        return;
    }

    if(password.length < 6) {
        showError('密码至少6位');
        return;
    }

    const users = JSON.parse(localStorage.getItem('users')) || [];
    const existingUser = users.find(u => u.username === username);
    
    if(existingUser) {
        showError('用户名已存在');
        return;
    }

    users.push({
        username,
        email,
        password,
        createdAt: new Date().toISOString()
    });

    localStorage.setItem('users', JSON.stringify(users));
    showSuccess('注册成功，请登录');
    setTimeout(() => {
        window.location.href = 'login.html';
    }, 1500);
});

// 登录功能
document.getElementById('loginForm').addEventListener('submit', (e) => {
    e.preventDefault();
    const username = document.getElementById('loginUsername').value;
    const password = document.getElementById('loginPassword').value;

    const users = JSON.parse(localStorage.getItem('users')) || [];
    const user = users.find(u => 
        u.username === username && u.password === password
    );

    if(user) {
        localStorage.setItem('currentUser', JSON.stringify(user));
        window.location.href = 'index.html';
    } else {
        showError('用户名或密码错误');
    }
});

// 辅助函数
function validateEmail(email) {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

function showError(message) {
    Swal.fire({
        title: '错误',
        text: message,
        icon: 'error',
        confirmButtonText: '确定'
    });
}

function showSuccess(message) {
    Swal.fire({
        title: '成功',
        text: message,
        icon: 'success',
        timer: 1500
    });
}
